package com.mrkun.vueshop.controller;

import com.github.pagehelper.PageInfo;
import com.mrkun.vueshop.DTO.UserDTO;
import com.mrkun.vueshop.mapper.UserMapper;
import com.mrkun.vueshop.model.User;
import com.mrkun.vueshop.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author by yong
 * @date 2020/3/15
 */
@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public UserDTO login(@RequestBody User user) {
        User one = userMapper.login(user.getUsername(), user.getPassword());
        UserDTO userDTO = new UserDTO();
        if (one == null){
            userDTO.setMsg("failure");
        }else{
            BeanUtils.copyProperties(one,userDTO);
            userDTO.setMsg("success");
        }
        return userDTO;
    }

    @PostMapping("/register")
    public Map<String, String> register(@RequestBody User user) {
        //使用currentHashMap保证线程安全
        Map<String, String> data = new ConcurrentHashMap<>(1);
        try {
            user.setRole("consumer");
            user.setMoney(new BigDecimal(0));
            userMapper.addUser(user);

            data.put("msg", "success");
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            data.put("msg", "failure");
            return data;
        }
    }


    @GetMapping("/getCount")
    public Integer getCount(){
        return userMapper.getCount();
    }

    @GetMapping("/search/{id}")
    public User search(@PathVariable("id") Integer id){
        return userMapper.findOne(id);
    }

    @PostMapping("/update")
    public String update(@RequestBody User user){
        try{
            userMapper.updateUser(user);
        }catch (Exception e){
            e.printStackTrace();
            return "failure";
        }
        return "success";
    }

    @GetMapping("/userPage/{page}/{size}")
    public PageInfo<User> page(@PathVariable("page")Integer page, @PathVariable("size")Integer size,
                               @RequestParam("searchName")String searchName){
       return userService.getPageUser(page,size,"%"+searchName.trim()+"%");
    }

    @DeleteMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id")Integer id){
        try{
            userMapper.deleteUserById(id);
        }catch (Exception e){
            e.printStackTrace();
            return "failure";
        }
        return "success";
    }
}
